#include <errno.h>

#include <linux/sched.h>
#include <linux/kernel.h>

int sys_open(const char *filename, int flag, int mode)
{
    struct m_inode *inode;
    struct file *f;
    int i, fd;

    for(fd = 0; fd < NR_OPEN; fd++)
        if (!current->filp[fd])
            break;
    if (fd >= NR_OPEN)
        return -EINVAL;
    
    f = 0 + file_table;
    for (i = 0 ; i < NR_FILE; i++, f++)
        if (!f->f_count)
            break;
    if (i >= NR_FILE)
        return -EINVAL;
    
    current->filp[fd] = f;
    
    i = open_namei(filename, flag, mode, &inode);
    if (i < 0) {
        current->filp[fd] = NULL;
        return i;
    }
    
    f->f_mode = inode->i_mode;
    f->f_flags = flag;
    f->f_count = 1;
    f->f_inode = inode;
    f->f_pos = 0;
    printk("open file successfully!\n");
    return (fd);
}